package security;

import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.Mode;
import cn.hutool.crypto.Padding;
import cn.hutool.crypto.symmetric.AES;

/**
 * @author wangmaolin1
 * @date 2022/1/13 下午10:11
 */
public class AESUtil {

    public static AES aes = new AES(Mode.CBC, Padding.PKCS5Padding, "oiNnEMxJmQ/fbX/z".getBytes(), "oiNnEMxJmQ/fbX/z".getBytes());

    public static String encrypt(String source) {
        return aes.encryptHex(source);
    }

    public static String decryptStr(String encrypted) {
        if (StrUtil.isEmpty(encrypted) || StrUtil.NULL.equals(encrypted)) {
            return encrypted;
        }
        encrypted = aes.decryptStr(encrypted);

        return encrypted;
    }


    public static String decryptValue(String value) {
        if (StrUtil.isBlank(value)) {
            return value;
        }
        return decryptStr(value);
    }

    public static String byteToHexString(byte[] bytes) {
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < bytes.length; i++) {
            String strHex = Integer.toHexString(bytes[i]);
            if (strHex.length() > 3) {
                sb.append(strHex.substring(6));
            } else {
                if (strHex.length() < 2) {
                    sb.append("0" + strHex);
                } else {
                    sb.append(strHex);
                }
            }
        }
        return sb.toString();
    }

    public static void main(String[] args) {
//        SecretKey aes = SecureUtil.generateKey("", 128);
//        byte[] encoded = aes.getEncoded();
//        System.out.println(byteToHexString（);
        String encrypt = encrypt("");
        String s = decryptStr(encrypt);
        System.out.println(encrypt);
        System.out.println(s);
    }
}
